using MediatR;
using RBAC.Api.Demain.ContentManagement;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Read.Command.ContentManagement;

namespace RBAC.Api.Read.CommandHandler.ContentManagement
{
    public class ShowDepartmentsCommandHandler : IRequestHandler<ShowDepartmentsCommand, APIResult<APIPagin<DepartmentModel>>>
    {
        private readonly IBaseRepositry<DepartmentModel> baseRepositry;

        public ShowDepartmentsCommandHandler(IBaseRepositry<DepartmentModel> baseRepositry)
        {
            this.baseRepositry = baseRepositry;
        }

        public Task<APIResult<APIPagin<DepartmentModel>>> Handle(ShowDepartmentsCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPagin<DepartmentModel>> result = new APIResult<APIPagin<DepartmentModel>>();
            result.Code = ResultCode.Success;
            result.Message = "获取科室列表成功";

            // 构建查询条件
            var query = baseRepositry.GetAll();

          

            // 根据父级科室ID查询
            if (request.ParentId.HasValue)
            {
                query = query.Where(x => x.ParentId == request.ParentId.Value);
            }

           

            // 按创建时间倒序排列
            query = query.OrderByDescending(x => x.CreateTime);

            // 计算总数
            int totalCount = query.Count();

            // 分页查询
            var list = query.Skip((request.PageIndex - 1) * request.PageSize)
                           .Take(request.PageSize)
                           .ToList();

            // 构建分页结果
            APIPagin<DepartmentModel> pagin = new APIPagin<DepartmentModel>();
            pagin.List = list;
            pagin.TotaleCount = totalCount;
            pagin.PageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);
            

            result.Data = pagin;

            return Task.FromResult(result);
        }
    }
}